package com.tz.actions.cart;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.tz.entity.Cart;
import com.tz.entity.OrderItem;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import sun.font.TrueTypeFont;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by heziqian on 2016/10/21.
 */
@Namespace("/")
public class DeleteitemAction extends ActionSupport{

    String ids;

    @Action(value = "deleteitem",
            results = {@Result(location="/cart.jsp"),
                    @Result(name = "input",location = "/cart.jsp")
            })
    public String execute() {

        String[] idArr = ids.split(":");

        ActionContext context=ActionContext.getContext();
        Map<String,Object> session=context.getSession();
        Cart cart=(Cart)session.get("cart");
        Set<OrderItem> items = cart.getItems();


        int count = 0;
        double totalPrice = 0;

        boolean flag = true;
        Set<OrderItem> is = new HashSet<>();

        if (ids != null) {

            for (OrderItem o : items) {
                for (String id : idArr) {

                    if (o.getBook().getBookId().equals(Long.parseLong(id))) {
                        flag = false;
                    }

                }

                if (flag) {
                    is.add(o);
                    flag = true;
                }

                flag=true;
            }
        }



        if (is != null) {
            for (OrderItem t : is) {
                count += t.getCount();
                totalPrice += t.getTotalPrice();
            }
        }

        cart.setItems(is);
        cart.setCount(count);
        cart.setTotalPrice(totalPrice);

        session.put("cart",cart);

        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print("1");
        } catch (IOException e) {
            e.printStackTrace();
        }

        out.flush();
        out.close();

        return SUCCESS;

    }

    public String getIds() {
        return ids;
    }

    public void setIds(String ids) {
        this.ids = ids;
    }
}
